<template>
<q-page class="q-pa-sm">
    <q-expansion-item default-opened header-class="q-pa-none" class="q-pa-none">
        <template v-slot:header>
            <tips-title class="full-width text-subtitle1" title="基本信息" tipclass="bg-primary" lineColor="primary"></tips-title>
        </template>
        <div class="row">
            <div class="col-6 col-md-3 q-pa-sm">
                <div class="row shadow-10 items-center cardbg q-pa-md b-radius-md" style="min-height: 75px">
                    <div class="text-white text-subtitle1">
                        <span class="text-caption">项目总价： </span>{{ price
              }}{{ price == "暂无" ? "" : "元" }}
                    </div>
                </div>
            </div>
            <div class="col-6 col-md-3 q-pa-sm">
                <div class="row shadow-10 items-center cardbg q-pa-md b-radius-md" style="min-height: 75px">
                    <div class="row items-center text-white text-subtitle1">
                        <span class="text-caption">抽成比例： </span>
                        <q-select dark v-model="discount" :options="discountOptions" value="value" @input="handleSetDiscount" dense emit-value map-options />
                    </div>
                </div>
            </div>
            <div class="col-6 col-md-3 q-pa-sm">
                <div class="row shadow-10 items-center cardbg q-pa-md b-radius-md text-subtitle1" style="min-height: 75px">
                    <span class="text-caption">公司利润： </span>
                    {{ revenue }}
                </div>
            </div>
            <div class="col-6 col-md-3 q-pa-sm">
                <div class="row shadow-10 items-center cardbg q-pa-md b-radius-md text-subtitle1" style="min-height: 75px">
                    <span class="text-caption"> 分配总额： </span>
                    {{ profit }}
                </div>
            </div>
        </div>
    </q-expansion-item>

    <q-expansion-item default-opened header-class="q-pa-none" class="q-pa-none">
        <template v-slot:header>
            <tips-title class="full-width text-subtitle1" btnColor="amber" title="成本" :isAdd="user.right>=5" :isCaption="true" @add="handleAddReimburse" :capTitle="'合计：￥' + costTotal" capClass="text-amber-6 text-bold" tipclass="bg-amber-6" lineColor="amber"></tips-title>
        </template>
        <q-table dark class="q-px-sm" :data="reimburseList" :columns="reimBurseColumns" row-key="name"  :rows-per-page-options="[3, 5,10,20]">
            <template v-slot:body="props">
                <q-tr :props="props">
                    <q-td key="remark" :props="props">
                        {{ props.row.remark }}
                    </q-td>
                    <q-td key="ctime" :props="props">
                        {{ props.row.fundtime }}
                    </q-td>
                    <q-td key="username" :props="props">
                        {{ props.row.username }}
                    </q-td>
                    <q-td key="amount" :props="props">
                        {{ props.row.amount }}
                    </q-td>
                    <q-td key="content" :props="props">
                        {{ props.row.content }}
                    </q-td>
                </q-tr>
            </template>
        </q-table>
    </q-expansion-item>
    <q-expansion-item default-opened header-class="q-pa-none" class="q-pa-none">
        <template v-slot:header>
            <tips-title class="q-my-md text-subtitle1 full-width" title="人员酬劳明细" tipclass="bg-blue" lineColor="blue" :isCaption="true" :isEdit="user.right>=5" @edit="handleWidgetDialog" editBtnColor="blue" :capTitle="'合计：￥' + widgetTotal" capClass="text-blue text-bold"></tips-title>
        </template>
        <q-table dark class="q-px-sm" :data="memberList" :columns="columns" row-key="name" hide-bottom>
            <template v-slot:body="props">
                <q-tr :props="props">
                    <q-td key="name" :props="props">
                        <q-avatar size="25px" class="q-mr-sm">
                            <img :src="props.row.avatar" />
                        </q-avatar>
                        {{ props.row.username }}
                    </q-td>
                    <q-td key="detail" :props="props">
                        <div class="row items-start q-gutter-sm full-width justify-center">
                            <div class="row " v-for="(item,index) in props.row.widgetList" :key="index">

                                <q-badge class="text-grey" outline> {{ item.remark }}:￥{{ item.amount }}</q-badge>

                            </div>
                        </div>

                    </q-td>
                    <q-td key="total" :props="props">
                        {{ props.row.widgetTotal }}
                    </q-td>

                </q-tr>
            </template>
        </q-table>
    </q-expansion-item>
    <my-dialog :isDark="true" :isOpen="isSetWidgetDialog" :footInfo="'剩余：'+remindWidget.toFixed(2)" title="设置人员酬劳" @close="isSetWidgetDialog = false" @cancel="handleCancelWidgetDialog" @submit="handleSetWidget">
        <template #foot>
            <div class="q-pa-sm">
                总计：￥{{ widgetTotal.toFixed(2) }}
                <span class="q-ml-sm">人均：￥{{(widgetTotal/memberList.length).toFixed(2) }}</span>

            </div>
        </template>
        <template #content>
            <div class="q-pa-sm">
                <q-expansion-item v-for="item in memberList" :key="item.eid" default-opened header-class="q-pa-none" class="q-pa-none">
                    <template v-slot:header>
                        <tips-title class="q-my-md text-subtitle1 text-white full-width" :title="item.username" tipclass="bg-primary" lineColor="primary" :isCaption="true" :isAdd="true" @add="handleAddMemberWidget(item)" editBtnColor="primary" :capTitle="'合计：￥' + item.widgetTotal" capClass="text-primary text-bold"></tips-title>
                    </template>
                    <div class="q-pa-md" v-if="item.widgetList.length > 0">
                        <div class="row q-col-gutter-sm q-mb-sm" v-for="(i, index) in item.widgetList" :key="index">
                            <div class="col-1">
                                <q-badge outline class="q-pa-sm fit">{{ index + 1 }}</q-badge>
                            </div>

                            <q-input dense class="col-3" dark outlined label="金额" v-model="i.amount" @input="handleChangeAmount($event, i)" type="number"></q-input>
                            <q-input dense class="col-grow" dark outlined label="工作内容" v-model="i.remark" @input="handleChangeRemark()"></q-input>
                            <div class="col-1">
                                <q-btn v-if="index!=0" round dense outline color="red-3" @click="handleDeleteWidgetInfo(item,index)" icon="delete"></q-btn>

                            </div>
                        </div>
                    </div>
                </q-expansion-item>
            </div>
        </template>
    </my-dialog>
    <my-dialog :isDark="true" :isOpen="isReimAddDialog" title="设置成本明细" @close="isReimAddDialog = false" @cancel="handleCancelAddReimDialog" @submit="handleSetReim">
        <template #content>
            <div class="q-pa-sm">
                <q-input dark class="col-12 col-md-6" rounded outlined type="number" v-model="form.amount" label="金额 *" suffix="元" lazy-rules :rules="[(val) => (val && val.length > 0) || '请输入金额']" />

                <q-input dark class="col-12 col-md-6" rounded outlined v-model="form.remark" label="费用名称 *" lazy-rules :rules="[
              (val) => (val && val !== '' && val.length > 0) || '请输入原因',
            ]" />
                <q-input dark class="col-12 col-md-6" rounded outlined v-model="form.fundtime" label="费用发生时间 *" lazy-rules :rules="[
              (val) =>
                (val && val !== '' && val.length > 0) || '请输入费用发生时间',
            ]">
                    <q-popup-proxy ref="qDateProxy" transition-show="scale" transition-hide="scale" :breakpoint="2000">
                        <q-date v-model="form.fundtime" @input="handleselect">
                            <div class="row items-center justify-end">
                                <q-btn v-close-popup label="关闭" color="primary" flat />
                            </div>
                        </q-date>
                    </q-popup-proxy>
                    <template v-slot:append>
                        <q-icon name="event" class="cursor-pointer"> </q-icon>
                    </template>
                </q-input>
                <q-input dark class="col-12 col-md-6" v-model="form.content" rounded outlined type="textarea" label="费用说明" />
            </div>
        </template>
    </my-dialog>
    <my-dialog :isDark="true" :footInfo="'原价：' + price" :isOpen="isPriceEditDialog" title="修改价格" @close="isPriceEditDialog = false" @cancel="isPriceEditDialog = false" @submit="handleUpdatePrice">
        <template #content>
            <div class="q-pa-sm">
                <q-input dark label="价格" type="number" v-model="newPrice"></q-input>
            </div>
        </template>
    </my-dialog>
</q-page>
</template>

<script>
import {
    getPrice,
    setPrice,
    getReimBurseList,
    setProjectReimburse,
    setMemberWidget,
    getMemberWidget,
    setDiscount
} from "assets/api/studio/pm";
import {
    formatQuoteData
} from "assets/utils/pm";
const columns = [{
        name: "name",
        required: true,
        label: "姓名",
        align: "left",
        field: "username",
        format: (val) => `${val}`,
    },

    {
        name: "detail",
        align: "center",
        label: "详情",
        field: "detail"
    },
    {
        name: "total",
        align: "right",
        label: "总计",
        field: "total"
    },
];
const reimBurseColumns = [{
        name: "remark",
        required: true,
        label: "费用名称",
        align: "left",
        field: "remark",
    },
    {
        name: "ctime",
        align: "center",
        label: "创建时间",
        field: "ctime"
    },
    {
        name: "username",
        align: "center",
        label: "创建人",
        field: "username"
    },

    {
        name: "amount",
        align: "center",
        label: "价格",
        field: "amount"
    },
    {
        name: "content",
        align: "center",
        label: "备注",
        field: "content"
    },
];

export default {
    // name: 'PageName',
    components: {
        QuoteList: () => import("components/QuoteList"),
    },

    data() {
        return {
            pid: "",
            quoteList: [],
            pageNum: 1,
            pageSize: 10,
            isLoad: true,
            isEmpty: true,
            noMoreQuote: false,
            isRefresh: false,
            price: "暂无",
            isPriceEditDialog: false,
            newPrice: 0,

            columns,
            projectInfo: null,
            memberList: [],
            discount: 20,
            discountOptions: [{
                    label: "10%",
                    value: 10,
                },
                {
                    label: "15%",
                    value: 15,
                },
                {
                    label: "20%",
                    value: 20,
                },
                {
                    label: "25%",
                    value: 25,
                },
                {
                    label: "30%",
                    value: 30,
                },
                {
                    label: "35%",
                    value: 35,
                },
                {
                    label: "40%",
                    value: 40,
                },
                {
                    label: "45%",
                    value: 45,
                },
                {
                    label: "50%",
                    value: 50,
                },
            ],
            revenue: 0,
            profit: 0,
            costTotal: 0,
            widgetTotal: 0,
            memberWidgetTotal: 0,
            remindWidget: 0,
            reimBurseColumns,

            reimburseList: [],
            isReimAddDialog: false,
            form: {
                amount: null,
                fundtime: null,
                reason: null,
                content: null,
            },
            isSetWidgetDialog: false,
            widgetList: [],
        };
    },
    watch: {
        discount(v) {
            //console.log(v, "discount");
            this.calProfit();
        },
        reimburseList() {
            this.calCost();
        },
    },
    created() {
        this.pid = this.$route.params.pid;
        this.projectInfo = this.$storage.getItem(this.pid);
        // this.projectInfo = this.$store.state.projectinfo;

        this.i_name = setInterval(() => {
            this.projectInfo = this.$storage.getItem(this.pid);

            if (this.projectInfo.name) {
                let memberList = this.projectInfo.memberList;
                //console.log(this.projectInfo, "load projectinfo");
                //console.log(this.memberList);
                console.log(this.projectInfo);

                this.memberList = memberList;
                this.loadPrice();
                this.loadReimburseList();
                this.loadMemberWidget()
                clearInterval(this.i_name)
            }

        }, 500);

        this.user = this.$store.state.user;
        // console.log(this.user,'user');

    },
    beforeDestroy() {
        this.$q.loading.hide();
    },
    methods: {
        handleSetDiscount() {
            console.log(this.discount);
            setDiscount({
                pid: this.pid,
                discount: this.discount
            }).then(res => {
                if (res.data.code == 1) {
                    this.$message.success('设置成功！')
                } else {
                    this.$message.error('设置成功！')
                }
            })
        },
        formatMemberList() {

        },

        loadMemberWidget() {
            getMemberWidget({
                pid: this.pid
            }).then(res => {
                let data = res.data.data
                console.log(data, 'member');

                if (data.length > 0) {
                    let i = setInterval(() => {
                        if (this.memberList.length > 0) {
                            clearInterval(i)
                            this.memberList.forEach(item => {
                                item.widgetList = []
                                data.forEach(i => {

                                    if (i.eid && i.eid == item.eid) {
                                        item.widgetList.push({
                                            amount: i.amount,
                                            remark: i.remark
                                        })
                                        item.widgetTotal = i.total

                                    }
                                    if (i.openid && i.openid == item.openid) {
                                        item.widgetList.push({
                                            amount: i.amount,
                                            remark: i.remark
                                        })
                                        item.widgetTotal = i.total
                                    }
                                })
                            })
                            this.refreshMemberList()

                        }
                    }, 500)

                } else {
                    this.memberList.forEach((item) => {
                        item.widgetList = [];
                        item.widgetList.push({
                            amount: 0,
                            remark: "",
                        });
                        item.widgetTotal = 0;
                    });
                }
            })
        },
        handleDeleteWidgetInfo(item, index) {
            item.widgetList.splice(index, 1)
            this.refreshMemberList()
        },
        refreshMemberList() {
            let memberList = this.memberList;
            let arr = [];
            var memberWidgetTotal = 0
            memberList.forEach((item) => {

                var widgetTotal = 0;
                item.widgetList.forEach((i) => {
                    widgetTotal = widgetTotal + Number(i.amount);
                });
                item.widgetTotal = widgetTotal

                memberWidgetTotal = memberWidgetTotal + Number(item.widgetTotal)

                arr.push(item);
            });
            this.memberWidgetTotal = memberWidgetTotal
            this.remindWidget = this.widgetTotal - this.memberWidgetTotal
            this.memberList = arr;
        },
        handleChangeAmount(e, i) {
            console.log(e, i);
            this.refreshMemberList();
        },
        handleChangeRemark() {
            this.refreshMemberList()
        },
        handleAddMemberWidget(item) {
            console.log(item);

            item.widgetList.push({
                amount: 0,
                remark: "",
            });
            var widgetTotal = 0;
            item.widgetList.forEach((item) => {
                widgetTotal = widgetTotal + Number(item.amount);
            });
            item.widgetTotal = widgetTotal;
            this.refreshMemberList();
        },
        handleWidgetDialog() {
            this.isSetWidgetDialog = true;
            this.calTotal()
        },
        handleCancelWidgetDialog() {},
        handleSetWidget() {
            console.log('setWidget', this.memberList);
            setMemberWidget({
                pid: this.pid,
                memberWidget: this.memberList
            }).then(res => {
                if (res.data.code == 1) {
                    this.isSetWidgetDialog = false;

                    this.$message.success(res.data.msg)
                } else {
                    this.$message.error(res.data.msg)
                }
            })
        },
        handleselect() {
            this.$refs["qDateProxy"].hide();
        },
        handleCancelAddReimDialog() {
            this.isReimAddDialog = false;
            this.form = {
                amount: null,
                fundtime: null,
                reason: null,
                content: null,
            };
        },
        handleSetReim() {
            this.$q.loading.show();
            let reqData = {
                amount: this.form.amount,
                remark: this.form.remark,
                fundtime: this.form.fundtime,
                content: this.form.content,
                pid: this.pid,
            };
            // //console.log(reqData);
            setProjectReimburse(reqData).then((res) => {
                this.$q.loading.hide();
                if (res.data.code == 1) {
                    this.reimburseList.push({
                        ...reqData,
                        username: this.user.username,
                    });
                    this.handleCancelAddReimDialog();
                    this.$message.success(res.data.msg);
                } else {
                    this.$message.error(res.data.msg);
                }
            });
        },
        handleAddReimburse() {
            this.isReimAddDialog = true;
        },
        loadReimburseList() {
          this.reimburseList=[]
            getReimBurseList({
                pid: this.pid
            }).then((res) => {
                let data = res.data.data;
                console.log(data);
                if (data.length > 0 || data[1].length > 0) {
                    this.reimburseList = data[0].concat(data[1]);
                    this.calCost();
                }
            });
        },
        calTotal() {
            this.widgetTotal = this.profit - this.costTotal;
            this.remindWidget = this.widgetTotal - this.memberWidgetTotal
        },
        calCost() {
            var total = 0;
            this.reimburseList.forEach((item) => {
                total = total + Number(item.amount);
            });
            this.costTotal = total;
            this.calTotal()
        },
        calProfit() {
            this.revenue = (Number(this.price) * Number(this.discount)) / 100;
            this.profit = Number(this.price) - this.revenue;
            this.calTotal()
        },
        handlePriceEditDialog() {
            this.isPriceEditDialog = true;
            this.newPrice = this.price;
        },
        handleUpdatePrice() {
            if (this.newPrice) {
                this.$q.loading.show();
                setPrice({
                    pid: this.pid,
                    price: this.newPrice,
                }).then((res) => {
                    this.$q.loading.hide();
                    if (res.data.code == 1) {
                        this.$message.success(res.data.msg);
                        this.price = this.newPrice;
                        this.isPriceEditDialog = false;
                    } else {
                        this.$message.error();
                    }
                });
            }
        },
        loadPrice() {
            getPrice({
                pid: this.pid,
                pageNum: this.pageNum,
                pageSize: this.pageSize,
            }).then((res) => {
                //console.log(res.data.data);
                let data = res.data.data;
                this.isLoad = false;
                let price = Number(data[0][0].price);
                if (price > 0 && price) {
                    if (this.projectInfo.discount && this.projectInfo.discount > 0) {
                        this.discount = Number(this.projectInfo.discount);
                    } else {
                        if (price > 0 && price <= 2000) {
                            this.discount = 10;
                        } else if (price > 2000 && price <= 4000) {
                            this.discount = 15;
                        } else if (price > 4000 && price <= 6000) {
                            this.discount = 20;
                        } else if (price > 6000 && price <= 8000) {
                            this.discount = 25;
                        } else if (price > 8000 && price <= 10000) {
                            this.discount = 30;
                        } else if (price > 10000 && price <= 30000) {
                            this.discount = 35;
                        } else if (price > 30000 && price <= 50000) {
                            this.discount = 40;
                        } else if (price > 50000 && price <= 100000) {
                            this.discount = 45;
                        } else if (price > 100000) {
                            this.discount = 50;
                        }

                    }

                    this.price = price;

                    this.calProfit();
                }

                if (data[1].length == 0) {
                    this.noMoreProject = true;
                    this.isEmpty = true;
                } else if (data[1].length > 0) {
                    this.isEmpty = false;

                    this.quoteList = formatQuoteData(data[1]);
                }
            });
        },

        handleRefreshQuote(v) {
            this.pageNum += 1;
            //console.log("refresh", this.pageNum);

            getPrice({
                pid: this.pid,
                pageNum: this.pageNum,
                pageSize: this.pageSize,
            }).then((res) => {
                let data = res.data.data;
                if (data[1].length > 0) {
                    this.isEmpty = false;
                    this.quoteList = formatQuoteData(data[1]);
                    this.isRefresh = true;
                } else {
                    this.noMoreQuote = true;
                    this.$refs["quote-list"].$children[0].stop();
                }
            });
        },
    },
};
</script>

<style>
.cardbg {
    background-image: linear-gradient(30deg,
            #6668d781 20px,
            #2558ff6b,
            #08b6bc6e);
}
</style>
